import type { ConfigEnv, UserConfig } from 'vite'
import { resolve } from 'node:path'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import UnoCSS from 'unocss/vite'
import autoImport from 'unplugin-auto-import/vite'
import components from 'unplugin-vue-components/vite'
import { loadEnv } from 'vite'
import viteCompression from 'vite-plugin-compression'
import { createHtmlPlugin } from 'vite-plugin-html'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import ZipPack from 'vite-plugin-zip-pack'

function pathResolve(dir: string) {
  return resolve(process.cwd(), '.', dir)
}

export default ({ mode }: ConfigEnv): UserConfig => {
  const env = loadEnv(mode, process.cwd()) as ImportMetaEnv
  const outDir = env.VITE_APP_CONFIG_OUTDIR
  return {
    base: env.VITE_APP_CONFIG_BASE,
    // 路径重定向
    resolve: {
      alias: [
        {
          find: '@',
          replacement: pathResolve('src'),
        },
      ],
    },
    // 全局 css 注册
    css: {
      preprocessorOptions: {
        less: {
          additionalData: '@import "./src/styles/build/variables.module.less";',
          javascriptEnabled: true,
        },
      },
    },
    server: {
      open: true,
      port: 5201,
      hmr: {
        overlay: false,
      },
      host: '0.0.0.0',
      proxy: {
        [env.VITE_APP_BASE_API_PROXY]: {
          target: env.VITE_APP_BASE_API, // 代理接口
          changeOrigin: true,
          rewrite: path => path.replace(new RegExp(`^${env.VITE_APP_BASE_API_PROXY}`), ''),
        },
      },
    },
    plugins: [
      vue(),
      vueJsx(),
      UnoCSS(),
      autoImport({
        imports: ['vue', 'vue-router', '@vueuse/core', 'pinia'],
        dts: 'typings/auto-imports.d.ts', // 生成 `auto-import.d.ts` 全局声明
      }),
      // https://github.com/antfu/unplugin-vue-components 自动导入组件
      components({
        version: 3,
        dirs: ['src/components'],
        dts: 'typings/components.d.ts',
      }),
      // 使用本地svg，需要结合Icon组件
      createSvgIconsPlugin({
        iconDirs: [pathResolve('src/assets/svgs')],
        symbolId: 'icon-[dir]-[name]',
        svgoOptions: true,
      }),
      // html注入
      createHtmlPlugin({
        inject: {
          data: {
            VITE_APP_TITLE: env.VITE_APP_TITLE,
          },
        },
      }),
      // 开启gzip压缩
      viteCompression({
        verbose: true,
        disable: false,
        threshold: 1024 * 10, // 跳过小于10kb的文件
        algorithm: 'gzip',
        ext: '.gz',
        success() {
          // 自动压缩成zip
          // @ts-ignore 骚操作：ZipPack按正常的放在plugins里始终比Compression早，也无法通过vite常规配置控制执行顺序，这里通过查看ZipPack的源码，强制获取closeBundle钩子，在compression success后再调用
          const { closeBundle } = ZipPack({
            inDir: outDir,
            pathPrefix: 'dist',
            outFileName: `${outDir}.zip`,
          })
          closeBundle?.handler()
        },
      }),
    ],
    build: {
      outDir,
      minify: 'terser', // 如果需要用terser混淆，可打开这两行
      terserOptions: {
        compress: {
          drop_debugger: env.VITE_APP_CONFIG_DROP_DEBUGGER == 'true',
          drop_console: env.VITE_APP_CONFIG_DROP_CONSOLE == 'true',
        },
      },
    },
  }
}
